package com.wu.framework.gateway.config;

import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: swagger 动态资源配置
 * @author: 吴佳伟
 * @date: 2021/5/24
 */
@Configuration
@Primary
public class DynamicSwaggerResourceProvider implements SwaggerResourcesProvider {

    private final DiscoveryClientRouteLocator routeLocator;

    public DynamicSwaggerResourceProvider(DiscoveryClientRouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        routeLocator.getRoutes().forEach(
                route -> resources.add(createResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")))
        );
        return resources;
    }

    private SwaggerResource createResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}